package com.weitu.majorHazard.technicalReport.controller;

import com.weitu.accessory.bean.AccessoryPackageInfo;
import com.weitu.accessory.service.AccessoryUtilService;
import com.weitu.base.annotaion.SystemLog;
import com.weitu.base.controller.BaseController;
import com.weitu.majorHazard.technicalReport.entity.TechnicalReport;
import com.weitu.majorHazard.technicalReport.service.TechnicalReportService;
import com.weitu.paging.DataGridPagination;
import com.weitu.permission.user.entity.User;
import com.weitu.plugin.PageView;
import com.weitu.util.AjaxResult;
import com.weitu.util.DateTimeUtil;
import com.weitu.util.IDGenerator;
import com.weitu.workflow.definition.constant.FlowDefConstants;
import com.weitu.workflow.flowBusiness.constant.FlowBusinessConstants;
import com.weitu.workflow.flowManagement.entity.WorkflowReview;
import com.weitu.workflow.flowManagement.service.FlowManagementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by smp on 2017/4/24.
 */
@Controller
@RequestMapping(value = "majorHazard/technicalReport")
public class TechnicalReportController extends BaseController {
    private static final String MODULE_BATH_PATH=BASE_JSP_PATH+"majorHazard/technicalReport";

    private final TechnicalReportService technicalReportService;
    private final AccessoryUtilService accessoryUtilService;
    private final FlowManagementService flowManagementService;//流程管理service

    @Autowired
    public TechnicalReportController(TechnicalReportService technicalReportService,AccessoryUtilService accessoryUtilService,FlowManagementService flowManagementService){
        this.technicalReportService=technicalReportService;
        this.accessoryUtilService=accessoryUtilService;
        this.flowManagementService=flowManagementService;
    }

    /**
     * 条往列表页面
     * @return
     */
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public String list(){
        return MODULE_BATH_PATH+"/list";
    }

    /**
     * 列表页面
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/list",method = RequestMethod.POST)
    public Object listAjax(HttpServletRequest request){
        Map<String,Object> paramMap=new HashMap<String,Object>();
        putParametersIntoMap(paramMap);
        int count=this.technicalReportService.queryCount(paramMap);
        DataGridPagination dataGridPagination=DataGridPagination.getInstance(request,count);

        PageView pageView=dataGridPagination.getPageView();
        paramMap.put("pageView",pageView);

        List<TechnicalReport> technicalReportList=this.technicalReportService.queryList(paramMap);
        return dataGridPagination.flushDataGridData(technicalReportList);
    }

    /**
     * 跳到添加页面
     * @return
     */
    @RequestMapping(value = "/add",method = RequestMethod.GET)
    public ModelAndView add(){
        ModelAndView modelAndView=new ModelAndView();
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("addUserId",BaseController.getSessionUser().getId());
        map.put("addUserName",BaseController.getSessionUser().getRealName());
        map.put("addDeptId",BaseController.getSessionUser().getDepartment().getId());
        map.put("addDeptName",BaseController.getSessionUser().getDepartment().getName());
        map.put("addTime", DateTimeUtil.formatterDateTime());
        modelAndView.addObject("userMessage",map);
        modelAndView.setViewName(MODULE_BATH_PATH+"/add");
        return modelAndView;
    }

    /**
     * 添加技术报告
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @SystemLog(module = "技术报告",methods = "添加技术报告")
    public AjaxResult addAjax(TechnicalReport technicalReport){
        technicalReport.setId(IDGenerator.getId());
        technicalReport.setDelState(0);
        technicalReport.setState("未提交");
        boolean flag=this.technicalReportService.insertTechnicalReport(technicalReport);
        if(flag){
            return AjaxResult.success("添加成功");
        }else {
            return AjaxResult.fail("添加失败");
        }
    }

    /**
     * 跳到修改页面
     * @param id
     * @return
     */
    @RequestMapping(value = "/edit",method = RequestMethod.GET)
    public ModelAndView edit(String id){
        ModelAndView modelAndView=new ModelAndView();
        TechnicalReport technicalReport=this.technicalReportService.queryTechnicalReportById(id);
        List<AccessoryPackageInfo> accessoryList =  accessoryUtilService.queryAccessoryByBusinessId(id);
        modelAndView.addObject("technicalReport",technicalReport);
        modelAndView.addObject("accessoryList",accessoryList);
        modelAndView.addObject("uploadUserId",BaseController.getSessionUser().getId());
        modelAndView.setViewName(MODULE_BATH_PATH+"/edit");
        return modelAndView;
    }

    /**
     * 详情
     * @param id
     * @return
     */
    @RequestMapping(value = "/detail",method = RequestMethod.GET)
    public ModelAndView detail(String id){
        ModelAndView modelAndView=new ModelAndView();
        TechnicalReport technicalReport=this.technicalReportService.queryTechnicalReportById(id);
        List<AccessoryPackageInfo> accessoryList =  accessoryUtilService.queryAccessoryByBusinessId(id);
        modelAndView.addObject("technicalReport",technicalReport);
        modelAndView.addObject("accessoryList",accessoryList);
        modelAndView.addObject("uploadUserId",BaseController.getSessionUser().getId());
        modelAndView.setViewName(MODULE_BATH_PATH+"/detail");
        return modelAndView;
    }
    /**
     * 修改
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    @SystemLog(module = "技术报告",methods = "编辑技术报告")
    public AjaxResult editAjax(TechnicalReport technicalReport){
        technicalReport.setUpdateTime(DateTimeUtil.formatterDateTime());
        technicalReport.setUpdateUserId(BaseController.getSessionUser().getId());
        technicalReport.setUpdateDeptId(BaseController.getSessionUser().getDepartment().getId());
        boolean flag=this.technicalReportService.updateTechnicalReport(technicalReport);
        if(flag){
            return AjaxResult.success("编辑成功");
        }else{
            return AjaxResult.fail("编辑失败");
        }
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    @SystemLog(module = "技术报告",methods = "删除技术报告")
    public AjaxResult delete(String id){
        int count=this.technicalReportService.deleteTechnicalReport(id);
        if(count==1){
            return AjaxResult.success("删除成功");
        }else{
            return AjaxResult.fail("删除失败");
        }
    }

    /**
     * 提交
     * @param technicalReport
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/editSubmit",method = RequestMethod.POST)
    @SystemLog(module = "关键装置/要害部位_技术报告",methods = "提交技术报告")
    public AjaxResult editSubmit(TechnicalReport technicalReport) throws Exception{
        User loginUser=getSessionUser();

        Map<String, Object> paramMap = new HashMap<String, Object>();
        //获取前台参数
        getEditBasicFieldMap(paramMap);

        String id=paramMap.get("id").toString();//id
        //设置流程变量
        Map<String,String> dataMap=new HashMap<String, String>();
        String nextUserId=paramMap.get("nextUserId").toString();//第一环节处理人
        dataMap.put(FlowDefConstants.FLOW_FIRSTUSER_ID,nextUserId);
        String content="关键装置/技术报告审批流程";
        //启动流程实例
        flowManagementService.flowCreateAndRun(FlowBusinessConstants.BUSINESS_TECHNICAL_REPORT,id,content,loginUser.getName(),dataMap);

        return updateById(technicalReport);
    }
    private AjaxResult updateById(TechnicalReport technicalReport){
        Map<String, Object> paramMap = new HashMap<String, Object>();
        //获取前台参数
        getEditBasicFieldMap(paramMap);

        Integer result = technicalReportService.updateTechnicalReportBySubmit(technicalReport);
        if(result==1){
            return AjaxResult.success("提交成功");

        }else {
            return AjaxResult.fail("提交失败");
        }
    }

    /**
     * 只读
     * @param id
     * @return
     */
    @RequestMapping(value = "/details", method = RequestMethod.GET)
    public ModelAndView detailsView(String id) {
        if(null==id){
            Map<String, Object> paramMap = new HashMap<String, Object>();
            //获取参数
            putParametersIntoMap(paramMap);
            id=paramMap.get("businessId").toString();
        }
        TechnicalReport technicalReport = technicalReportService.queryTechnicalReportById(id);
        List<AccessoryPackageInfo> accessoryList =  accessoryUtilService.queryAccessoryByBusinessId(id);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName(MODULE_BATH_PATH + "/details");
        modelAndView.addObject("technicalReport", technicalReport);
        modelAndView.addObject("accessoryList",accessoryList);
        modelAndView.addObject("uploadUserId",BaseController.getSessionUser().getId());
        return modelAndView;
    }

    /**
     * 审核页面
     * @return
     */
    @RequestMapping(value = "/verify", method = RequestMethod.GET)
    public ModelAndView verifyView() {
        ModelAndView modelAndView = new ModelAndView();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        //获取参数
        putParametersIntoMap(paramMap);
        //工作项id
        String workItemId=paramMap.get("workItemId").toString();
        String businessId=paramMap.get("businessId").toString();
        //表单类型；0：只读表单；1：编辑表单
        int formType=paramMap.get("formType")!=null?Integer.parseInt(paramMap.get("formType").toString()):0;
        modelAndView.addObject("workItemId",workItemId);
        modelAndView.addObject("formType",formType);
        //获取意见信息
        WorkflowReview workflowReview=this.flowManagementService.queryWorkflowReviewByWorkItemId(workItemId);
        modelAndView.addObject("workflowReview",workflowReview);

        TechnicalReport technicalReport = technicalReportService.queryTechnicalReportById(businessId);
        List<AccessoryPackageInfo> accessoryList =  accessoryUtilService.queryAccessoryByBusinessId(businessId);

        modelAndView.setViewName(MODULE_BATH_PATH + "/details");
        modelAndView.addObject("technicalReport", technicalReport);
        modelAndView.addObject("accessoryList",accessoryList);
        modelAndView.addObject("uploadUserId",BaseController.getSessionUser().getId());
        return modelAndView;
    }

    /**
     * 审核
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/verify", method = RequestMethod.POST)
    @SystemLog(module = "关键装置/要害部位_技术报告", methods = "审批结束")
    public AjaxResult verifyView(HttpServletRequest request,TechnicalReport technicalReport)throws Exception {

        String workItemId=request.getParameter("workItemId");//获取工作项id
        //查询处理结果及意见
        WorkflowReview workflowReview=this.flowManagementService.getWorkflowReviewByRequest(request,"workflowReview",workItemId);
        //保存处理结果
        boolean boo=this.flowManagementService.saveWorkflowReview(workflowReview);

        //结束环节，继续流程向下执行
        if (boo){
            flowManagementService.workItemComplete(workItemId);
        }
        System.out.println(workflowReview.getComments());

        return updateById(technicalReport);
    }
}
